import {UploadRawFile, UploadRequestOptions} from "element-plus/es/components/upload/src/upload";
import {getUploadUrl, ProgressCallback} from "@/components/UploadFile/src/useUpload";
import {WebDiskDirVO} from "@/api/ai/webdiskdir";
import CryptoJS from "crypto-js";
import * as FileApi from "@/api/infra/file";
import axios from "axios";
import {WebDiskFileApi} from "@/api/ai/webdiskfile";

async function generateFileName(file: UploadRawFile) {
  // 读取文件内容
  const data = await file.arrayBuffer()
  const wordArray = CryptoJS.lib.WordArray.create(data)
  // 计算SHA256
  const sha256 = CryptoJS.SHA256(wordArray).toString()
  // 拼接后缀
  const ext = file.name.substring(file.name.lastIndexOf('.'))
  return `${sha256}${ext}`
}

export const useUploadToWebDisk=(onOk:(url:string,type:string,name:string)=>void)=>{
  // 后端上传地址
  const uploadUrl = getUploadUrl()
  const httpRequest = async (options: UploadRequestOptions) => {
    const fileName = await generateFileName(options.file)
    const presignedInfo = await FileApi.getFilePresignedUrl(fileName)
    return axios
      .put(presignedInfo.uploadUrl, options.file, {
        headers: {
          'Content-Type': options.file.type
        }
      })
      .then(() => {
        // 如果提供了进度回调函数，则调用，设置为100%
        onOk(presignedInfo.url,options.file.type,options.file.name)
        // 通知成功，数据格式保持与后端上传的返回结果一致
        return { data: presignedInfo.url }
      })
  }
  return {
    uploadUrl,
    httpRequest
  }
}
